<?php

namespace app\controller\crm;

use app\BaseController;
use app\common\DataPermissionHelper;
use app\service\CacheService;
use think\facade\Db;
use think\facade\Request;

class Customer extends BaseController
{
    /**
     * 获取客户列表（增强版）
     * 支持：高级筛选、统计信息、标签系统
     * 使用统一缓存服务：智能缓存键生成、权限隔离、统计监控
     */
    public function list()
    {
        $params = Request::param();
        $userId = $this->getUserId();

        // 使用统一CacheService的智能缓存策略
        $result = CacheService::smartCache('customer_list', function() use ($params) {
            return $this->executeCustomerListQuery($params);
        }, [
            'ttl' => 300,                    // 5分钟缓存
            'use_cache' => true,            // 启用缓存
            'force_refresh' => false,       // 不强制刷新
            'params' => $params,            // 传递查询参数用于智能缓存键生成
            'tags' => ['customer_list', 'customer_statistics'] // 添加标签支持
        ]);

        // 处理分页数据
        $data = $result['data'] ?? [];
        $paginationData = [
            'list' => $data['list'] ?? [],
            'total' => $data['total'] ?? 0,
            'page' => $data['page'] ?? 1,
            'limit' => $data['limit'] ?? 20
        ];

        // 返回分页结果（兼容原有接口）
        return $this->paginate($paginationData['list'], $paginationData['total'], $paginationData['page'], $paginationData['limit']);
    }

    /**
     * 执行客户列表查询（内部方法）
     */
    private function executeCustomerListQuery($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;

        // 构建查询
        $query = Db::name('crm_customer')
            ->alias('c')
            ->field('
                c.*,
                u.name as user_name,
                d.title as dept_name,
                c.followup_count,
                c.opportunity_count,
                c.order_count,
                c.total_order_amount,
                c.important_level,
                c.is_cooperation,
                c.cooperation_time,
                c.last_followup_time,
                c.last_order_time
            ')
            ->leftJoin('admin u', 'c.user_id = u.id')
            ->leftJoin('department d', 'u.did = d.id')
            ->where('c.delete_time', 0);

        // 关键词搜索
        if (!empty($params['keyword'])) {
            $keyword = $params['keyword'];
            $query->where(function($q) use ($keyword) {
                $q->where('c.name', 'like', "%{$keyword}%")
                  ->whereOr('c.legal_person', 'like', "%{$keyword}%")
                  ->whereOr('c.phone', 'like', "%{$keyword}%")
                  ->whereOr('c.email', 'like', "%{$keyword}%");
            });
        }

        // 高级筛选
        if (!empty($params['user_id'])) {
            $query->where('c.user_id', $params['user_id']);
        }

        if (!empty($params['department_id'])) {
            $query->where('u.did', $params['department_id']);
        }

        if (isset($params['level']) && $params['level'] !== '') {
            $query->where('c.level', $params['level']);
        }

        if (isset($params['important_level']) && $params['important_level'] !== '') {
            $query->where('c.important_level', $params['important_level']);
        }

        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('c.status', $params['status']);
        }

        if (isset($params['is_cooperation']) && $params['is_cooperation'] !== '') {
            $query->where('c.is_cooperation', $params['is_cooperation']);
        }

        if (!empty($params['industry'])) {
            $query->where('c.industry', $params['industry']);
        }

        if (!empty($params['scale'])) {
            $query->where('c.scale', $params['scale']);
        }

        if (!empty($params['source'])) {
            $query->where('c.source', $params['source']);
        }

        // 跟进状态筛选
        if (!empty($params['followup_filter'])) {
            $filter = $params['followup_filter'];
            if ($filter === '30_overdue') {
                // 超过30天未跟进
                $query->where('c.last_followup_time', '>', 0)
                      ->where('c.last_followup_time', '<', time() - 30*86400);
            } else {
                // X天内待跟进
                $days = (int)$filter;
                $query->where('c.last_followup_time', '>', time() - $days*86400);
            }
        }

        // 时间范围筛选
        if (!empty($params['create_time_start'])) {
            $query->where('c.create_time', '>=', $params['create_time_start']);
        }
        if (!empty($params['create_time_end'])) {
            $query->where('c.create_time', '<=', $params['create_time_end']);
        }

        if (!empty($params['cooperation_time_start'])) {
            $query->where('c.cooperation_time', '>=', $params['cooperation_time_start']);
        }
        if (!empty($params['cooperation_time_end'])) {
            $query->where('c.cooperation_time', '<=', $params['cooperation_time_end']);
        }

        // 标签筛选
        if (!empty($params['tags'])) {
            $tags = is_array($params['tags']) ? $params['tags'] : [$params['tags']];
            $query->where('c.customer_tags', 'like', '%' . $tags[0] . '%');
        }

        // 数据权限控制
        $userId = $this->getUserId();
        if ($userId > 0) {
            $userInfo = Db::name('admin')
                ->field('id, group_id, did')
                ->where('id', $userId)
                ->find();

            if ($userInfo) {
                // 数据权限控制：超级管理员拥有所有数据访问权限，不加限制
                if ($userInfo['group_id'] == 2) { // 部门经理
                    $query->where('u.did', $userInfo['did']);
                } elseif ($userInfo['group_id'] > 2) { // 销售人员
                    $query->where('c.user_id', $userId);
                }
                // group_id == 1 的超级管理员不添加任何权限限制
            }
        }

        $total = $query->count();
        $list = $query->order('c.id', 'desc')
            ->page($page, $limit)
            ->select();

        $list = $list ? $list->toArray() : [];

        // 格式化数据
        foreach ($list as &$item) {
            $item['days_since_followup'] = $this->calculateDaysSinceFollowup($item['last_followup_time']);
            $item['tags'] = $this->parseTags($item['customer_tags']);
            $item['create_time'] = $this->formatTime($item['create_time']);
            $item['update_time'] = $this->formatTime($item['update_time']);
            $item['cooperation_time'] = $this->formatTime($item['cooperation_time']);

            // 格式化行业名称
            $item['industry_name'] = $this->getIndustryName($item['industry']);

            // 格式化企业规模名称
            $item['scale_name'] = $this->getScaleName($item['scale']);
        }

        // 返回数组而不是paginate对象
        return [
            'list' => $list,
            'total' => $total,
            'page' => (int)$page,
            'limit' => (int)$limit
        ];
    }

    /**
     * 获取客户统计信息
     * 使用统一缓存服务：智能缓存、权限隔离、统计监控
     */
    public function statistics()
    {
        // 使用统一CacheService的智能缓存策略
        $result = CacheService::smartCache('customer_statistics', function() {
            return $this->executeCustomerStatisticsQuery();
        }, [
            'ttl' => 300,          // 5分钟缓存
            'use_cache' => true,   // 启用缓存
            'params' => [],        // 统计查询不需要额外参数
            'tags' => ['customer_statistics', 'customer_list'] // 添加标签支持
        ]);

        // 返回统计数据
        return $result['data'] ?? [];
    }

    /**
     * 执行客户统计查询（内部方法）
     */
    private function executeCustomerStatisticsQuery()
    {
        $userId = $this->getUserId();

        $baseQuery = Db::name('crm_customer')
            ->where('delete_time', 0);

        // 数据权限控制
        if ($userId > 0) {
            $userInfo = Db::name('admin')
                ->field('id, group_id, did')
                ->where('id', $userId)
                ->find();

            if ($userInfo) {
                // 数据权限控制：超级管理员拥有所有数据访问权限，不加限制
                if ($userInfo['group_id'] == 2) { // 部门经理
                    $baseQuery->where('user_id', 'in', function($q) use ($userInfo) {
                        $q->table('admin')->where('did', $userInfo['did'])->field('id');
                    });
                } elseif ($userInfo['group_id'] > 2) { // 销售人员
                    $baseQuery->where('user_id', $userId);
                }
                // group_id == 1 的超级管理员不添加任何权限限制
            }
        }

        $total = $baseQuery->count();

        $active = clone $baseQuery;
        $cooperation = clone $baseQuery;
        $toFollow = clone $baseQuery;
        $overdue = clone $baseQuery;

        $activeCount = $active->where('status', 'in', [1, 2])->count();
        $cooperationCount = $cooperation->where('is_cooperation', 1)->count();
        $toFollowCount = $toFollow->where('status', 2)->count();
        $overdueCount = $overdue->where('last_followup_time', '>', 0)
            ->where('last_followup_time', '<', time() - 7*86400)
            ->count();

        return [
            'total' => $total,
            'active' => $activeCount,
            'cooperation' => $cooperationCount,
            'to_follow' => $toFollowCount,
            'overdue' => $overdueCount,
            'conversion_rate' => $total > 0 ? round($cooperationCount / $total * 100, 2) : 0
        ];
    }

    /**
     * 新增客户
     */
    public function add()
    {
        // 记录详细的调试信息
        error_log("=== Customer add() called ===");
        $params = Request::param();
        error_log("Request params: " . print_r($params, true));
        error_log("customer_tags field exists: " . (isset($params['customer_tags']) ? 'YES' : 'NO'));
        if (isset($params['customer_tags'])) {
            error_log("customer_tags value: " . print_r($params['customer_tags'], true));
            error_log("customer_tags type: " . gettype($params['customer_tags']));
        }
        
        $userId = $this->getUserId();

        // 验证必填字段
        $required = ['name', 'phone'];
        foreach ($required as $field) {
            if (empty($params[$field])) {
                return $this->error("请填写{$field}");
            }
        }

        // 处理可选字段，确保不出现Undefined array key错误
        $id_type = $params['id_type'] ?? '';
        $id_number = $params['id_number'] ?? '';

        // 证件信息验证已取消（前端已取消验证）

        // 处理标签
        if (isset($params['customer_tags']) && is_array($params['customer_tags'])) {
            error_log("Processing customer_tags as array");
            $params['customer_tags'] = json_encode($params['customer_tags'], JSON_UNESCAPED_UNICODE);
            error_log("After JSON encode: " . print_r($params['customer_tags'], true));
        } else {
            error_log("customer_tags not array or not set");
        }

        $data = [
            'name' => $params['name'],
            'customer_type' => $params['customer_type'] ?? 2,
            'id_type' => $id_type,
            'id_number' => $id_number,
            'legal_person' => $params['legal_person'] ?? '',
            'phone' => $params['phone'],
            'email' => $params['email'] ?? '',
            'address' => $params['address'] ?? '',
            'industry' => $params['industry'] ?? '',
            'scale' => $params['scale'] ?? '',
            'source' => $params['source'] ?? '',
            'level' => $params['level'] ?? 1,
            'important_level' => $params['important_level'] ?? 1,
            'customer_tags' => $params['customer_tags'] ?? '',
            'next_followup_plan' => $params['next_followup_plan'] ?? '',
            'user_id' => $params['user_id'] ?? $userId,
            'department_id' => $params['department_id'] ?? 0,
            'contact_name' => $params['contact_name'] ?? '',
            'contact_phone' => $params['contact_phone'] ?? '',
            'remark' => $params['remark'] ?? '',
            'create_time' => time(),
            'update_time' => time()
        ];

        error_log("Final data for insert: " . print_r($data, true));

        $result = Db::name('crm_customer')->insert($data);

        if ($result) {
            // 清理相关缓存
            $this->clearCustomerCache();

            return $this->success('客户添加成功');
        }

        return $this->error('客户添加失败');
    }

    /**
     * 更新客户
     */
    public function update()
    {
        $params = Request::param();
        $id = $params['id'] ?? 0;

        if (!$id) {
            return $this->error('客户ID不能为空');
        }

        // 证件信息验证已取消（前端已取消验证）

        // 处理标签
        if (isset($params['customer_tags']) && is_array($params['customer_tags'])) {
            $params['customer_tags'] = json_encode($params['customer_tags'], JSON_UNESCAPED_UNICODE);
        }

        $data = [
            'name' => $params['name'],
            'customer_type' => $params['customer_type'] ?? 2,
            'id_type' => $params['id_type'] ?? null,
            'id_number' => $params['id_number'] ?? '',
            'legal_person' => $params['legal_person'] ?? '',
            'phone' => $params['phone'],
            'email' => $params['email'] ?? '',
            'address' => $params['address'] ?? '',
            'industry' => $params['industry'] ?? '',
            'scale' => $params['scale'] ?? '',
            'source' => $params['source'] ?? '',
            'level' => $params['level'] ?? 1,
            'important_level' => $params['important_level'] ?? 1,
            'customer_tags' => $params['customer_tags'] ?? '',
            'next_followup_plan' => $params['next_followup_plan'] ?? '',
            'lost_reason' => $params['lost_reason'] ?? '',
            'remark' => $params['remark'] ?? '',
            'update_time' => time()
        ];

        $result = Db::name('crm_customer')->where('id', $id)->update($data);

        if ($result !== false) {
            // 清理相关缓存
            $this->clearCustomerCache();

            return $this->success('客户更新成功');
        }

        return $this->error('客户更新失败');
    }

    /**
     * 批量操作
     */
    public function batch()
    {
        $params = Request::param();
        $ids = $params['ids'] ?? [];
        $action = $params['action'] ?? '';

        if (empty($ids) || empty($action)) {
            return $this->error('参数不完整');
        }

        switch ($action) {
            case 'assign_user':
                // 分配负责人
                $userId = $params['user_id'] ?? 0;
                if (!$userId) {
                    return $this->error('请选择负责人');
                }
                $result = Db::name('crm_customer')
                    ->where('id', 'in', $ids)
                    ->update(['user_id' => $userId, 'update_time' => time()]);
                break;

            case 'add_tag':
                // 添加标签
                $tag = $params['tag'] ?? '';
                if (!$tag) {
                    return $this->error('请输入标签');
                }

                $customers = Db::name('crm_customer')->where('id', 'in', $ids)->select();
                foreach ($customers as $customer) {
                    $tags = json_decode($customer['customer_tags'] ?? '[]', true) ?: [];
                    if (!in_array($tag, $tags)) {
                        $tags[] = $tag;
                    }
                    Db::name('crm_customer')
                        ->where('id', $customer['id'])
                        ->update(['customer_tags' => json_encode($tags, JSON_UNESCAPED_UNICODE)]);
                }
                $result = true;
                break;

            default:
                return $this->error('不支持的操作');
        }

        if ($result) {
            // 清理相关缓存
            $this->clearCustomerCache();

            return $this->success('批量操作成功');
        }

        return $this->error('批量操作失败');
    }

    // ================== 辅助方法 ==================

    private function calculateDaysSinceFollowup($lastFollowupTime)
    {
        if (!$lastFollowupTime || $lastFollowupTime <= 0) {
            return null;
        }
        return floor((time() - $lastFollowupTime) / 86400);
    }

    private function parseTags($tagsJson)
    {
        if (empty($tagsJson)) {
            return [];
        }
        
        // 添加调试信息
        error_log("parseTags input: " . print_r($tagsJson, true) . " (type: " . gettype($tagsJson) . ")");
        
        $tags = json_decode($tagsJson, true);
        error_log("parseTags output: " . print_r($tags, true) . " (type: " . gettype($tags) . ")");
        return is_array($tags) ? $tags : [];
    }

    private function formatTime($timestamp)
    {
        if (!$timestamp || $timestamp <= 0) {
            return '';
        }
        return date('Y-m-d H:i:s', $timestamp);
    }

    /**
     * 获取客户详情
     */
    public function detail()
    {
        $id = Request::param('id');

        // 如果使用 RESTful 风格，id 可能在路径参数中
        if (!$id) {
            $id = Request::param('id');
        }

        if (!$id) {
            return json(['code' => 1, 'message' => '客户ID不能为空']);
        }

        $customer = Db::name('crm_customer')
            ->alias('c')
            ->field('
                c.*,
                u.name as user_name,
                d.title as dept_name
            ')
            ->leftJoin('admin u', 'c.user_id = u.id')
            ->leftJoin('department d', 'u.did = d.id')
            ->where('c.id', $id)
            ->where(function($q) {
                $q->whereNull('c.delete_time')
                  ->whereOr('c.delete_time', 0)
                  ->whereOr('c.delete_time', '');
            })
            ->find();

        if (!$customer) {
            return json(['code' => 1, 'message' => '客户不存在']);
        }

        // 解析标签
        $customer['tags'] = $this->parseTags($customer['customer_tags'] ?? '');

        // 获取联系人列表
        $contacts = Db::name('crm_contact')
            ->where('customer_id', $id)
            ->where(function($q) {
                $q->whereNull('delete_time')
                  ->whereOr('delete_time', 0)
                  ->whereOr('delete_time', '');
            })
            ->order('is_primary', 'desc')
            ->order('id', 'desc')
            ->select();

        // 格式化联系人数据
        if ($contacts) {
            $contacts = $contacts->toArray();
            foreach ($contacts as &$contact) {
                $contact['create_time'] = $this->formatTime($contact['create_time'] ?? 0);
            }
        }

        $customer['contacts'] = $contacts ?: [];

        // 获取跟进记录统计
        $followupCount = Db::name('crm_followup')
            ->where('customer_id', $id)
            ->count();
        $lastFollowup = Db::name('crm_followup')
            ->where('customer_id', $id)
            ->order('followup_time', 'desc')
            ->value('followup_time');

        $customer['followup_stats'] = [
            'total_followup' => $followupCount,
            'last_followup' => $lastFollowup ? $this->formatTime($lastFollowup) : '-'
        ];

        // 获取订单统计
        $orderCount = Db::name('crm_order')
            ->where('customer_id', $id)
            ->count();
        $totalAmount = Db::name('crm_order')
            ->where('customer_id', $id)
            ->sum('total_amount');

        $customer['order_stats'] = [
            'total_order' => $orderCount,
            'total_amount' => $totalAmount ?: 0
        ];

        return json(['code' => 0, 'data' => $customer, 'message' => 'success']);
    }

    /**
     * 获取客户选项（用于下拉选择）
     */
    public function options()
    {
        $customers = Db::name('crm_customer')
            ->field('id, name')
            ->where('status', 1)
            ->where(function($q) {
                $q->whereNull('delete_time')
                  ->whereOr('delete_time', 0)
                  ->whereOr('delete_time', '');
            })
            ->select();

        $options = [];
        foreach ($customers as $customer) {
            $options[] = [
                'id' => $customer['id'],
                'name' => $customer['name'],
                'company_name' => $customer['name'], // 保持返回结构兼容
                'label' => $customer['name']
            ];
        }

        return json(['code' => 0, 'data' => $options, 'message' => 'success']);
    }

    /**
     * 创建客户
     */
    public function create()
    {
        $data = Request::param();
        $data['create_time'] = time();
        $data['user_id'] = session('user_id');

        $id = Db::name('crm_customer')->insertGetId($data);
        if ($id) {
            // 创建成功后清理相关缓存
            $this->clearCustomerCache();

            return json(['code' => 0, 'message' => '创建成功', 'data' => ['id' => $id]]);
        }

        return json(['code' => 1, 'message' => '创建失败']);
    }

    /**
     * 删除客户
     */
    public function delete()
    {
        $id = Request::param('id');

        $result = Db::name('crm_customer')
            ->where('id', $id)
            ->update(['delete_time' => time()]);

        if ($result !== false) {
            // 清理相关缓存
            $this->clearCustomerCache();

            return json(['code' => 0, 'message' => '删除成功']);
        }

        return json(['code' => 1, 'message' => '删除失败']);
    }

    /**
     * 获取行业选项
     */
    public function industryOptions()
    {
        $industries = Db::name('industry')
            ->where('status', 1)
            ->order('id', 'asc')
            ->select();

        // 转换格式，value转为字符串类型，与数据库中industry字段类型(varchar)保持一致
        $options = [];
        foreach ($industries as $industry) {
            $options[] = [
                'value' => (string)$industry['id'],
                'label' => $industry['title']
            ];
        }

        return json(['code' => 0, 'data' => $options, 'message' => 'success']);
    }

    /**
     * 获取企业规模选项
     */
    public function scaleOptions()
    {
        // value转为字符串类型，与数据库中scale字段类型(varchar)保持一致
        $options = [
            ['value' => '1', 'label' => '微型企业（10人以下）'],
            ['value' => '2', 'label' => '小型企业（10-50人）'],
            ['value' => '3', 'label' => '中型企业（50-200人）'],
            ['value' => '4', 'label' => '大型企业（200-500人）'],
            ['value' => '5', 'label' => '特大型企业（500人以上）']
        ];
        return json(['code' => 0, 'data' => $options, 'message' => 'success']);
    }

    /**
     * 获取客户来源选项
     */
    public function sourceOptions()
    {
        try {
            // 直接从数据库获取客户来源数据（不跨控制器调用，避免依赖问题）
            $sourceList = Db::name('customer_source')
                ->where('status', 1)
                ->where('delete_time', 0)
                ->order('sort', 'asc')
                ->select()
                ->toArray();
            
            // 转换格式为前端需要的 value/label 格式
            // 注意：value转为字符串类型，与数据库中source字段类型(varchar)保持一致
            $options = [];
            foreach ($sourceList as $item) {
                $options[] = [
                    'value' => (string)$item['id'],
                    'label' => $item['title']
                ];
            }
            
            return json(['code' => 0, 'data' => $options, 'message' => 'success']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'message' => '获取失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 获取负责人选项
     */
    public function userOptions()
    {
        $users = Db::name('admin')
            ->field('id, name, did')
            ->where('status', 1)
            ->where('id', '>', 1)  // 排除系统管理员
            ->select();

        $data = [];
        foreach ($users as $user) {
            $data[] = [
                'value' => $user['id'],
                'label' => $user['name'],
                'department_id' => $user['did']
            ];
        }

        return json(['code' => 0, 'data' => $data, 'message' => 'success']);
    }

    /**
     * 获取部门选项
     */
    public function departmentOptions()
    {
        $departments = Db::name('department')
            ->field('id, title')
            ->where('status', 1)
            ->select();

        $data = [];
        foreach ($departments as $dept) {
            $data[] = [
                'value' => $dept['id'],
                'label' => $dept['title']
            ];
        }

        return json(['code' => 0, 'data' => $data, 'message' => 'success']);
    }

    /**
     * 获取当前用户的审核记录
     */
    public function myReviews()
    {
        $params = Request::param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        $userId = $this->getUserId();

        if (!$userId) {
            return json(['code' => 0, 'data' => [], 'message' => '未登录或登录已过期']);
        }

        $result = [
            'list' => [],
            'total' => 0
        ];

        // 查询客户审核记录
        $customerReviewsQuery = Db::name('crm_customer_review')
            ->alias('r')
            ->field('r.*, u.name as user_name, c.name as customer_name')
            ->leftJoin('admin u', 'r.user_id = u.id')
            ->leftJoin('crm_customer c', 'r.customer_id = c.id')
            ->where('r.user_id', $userId);

        $customerTotal = $customerReviewsQuery->count();
        $customerList = $customerReviewsQuery->order('r.create_time', 'desc')
            ->page($page, $limit)
            ->select();

        if ($customerList) {
            $customerList = $customerList->toArray();
            foreach ($customerList as &$item) {
                $item['category'] = 'customer';
                $item['review_type_text'] = $this->getReviewTypeText($item['review_type']);
                $item['status_text'] = $this->getStatusText($item['status']);

                // 如果customer_name为空，从new_data中解析
                if (empty($item['customer_name']) && !empty($item['new_data'])) {
                    $newData = json_decode($item['new_data'], true);
                    $item['customer_name'] = $newData['name'] ?? '';
                }

                // 格式化时间
                $item['create_time'] = $this->formatTime($item['create_time']);
                $item['update_time'] = $this->formatTime($item['update_time']);
                $item['review_time'] = $this->formatTime($item['review_time']);

                // 解析变更详情
                $item['change_details'] = $this->parseChangeDetails($item);
            }
        }

        $result['list'] = array_merge($result['list'], $customerList ?: []);
        $result['total'] += $customerTotal;

        // 如果分页显示所有记录，需要合并联系人审核记录
        // 这里简单处理，在第一页时也返回联系人审核记录
        if ($page == 1) {
            $contactReviewsQuery = Db::name('crm_contact_review')
                ->alias('r')
                ->field('r.*, u.name as user_name, c.name as contact_name, cu.name as customer_name')
                ->leftJoin('admin u', 'r.user_id = u.id')
                ->leftJoin('crm_contact c', 'r.contact_id = c.id')
                ->leftJoin('crm_customer cu', 'r.customer_id = cu.id')
                ->where('r.user_id', $userId);

            $contactTotal = $contactReviewsQuery->count();
            $contactList = $contactReviewsQuery->order('r.create_time', 'desc')
                ->page($page, $limit)
                ->select();

            if ($contactList) {
                $contactList = $contactList->toArray();
                foreach ($contactList as &$item) {
                    $item['category'] = 'contact';
                    $item['review_type_text'] = $this->getReviewTypeText($item['review_type']);
                    $item['status_text'] = $this->getStatusText($item['status']);

                    // 如果字段为空，从new_data中解析
                    if (!empty($item['new_data'])) {
                        $newData = json_decode($item['new_data'], true);
                        if (empty($item['contact_name'])) {
                            $item['contact_name'] = $newData['name'] ?? '';
                        }
                    }

                    // 格式化时间
                    $item['create_time'] = $this->formatTime($item['create_time']);
                    $item['update_time'] = $this->formatTime($item['update_time']);
                    $item['review_time'] = $this->formatTime($item['review_time']);

                    // 解析变更详情
                    $item['change_details'] = $this->parseChangeDetails($item);
                }
            }

            $result['list'] = array_merge($result['list'], $contactList ?: []);
            $result['total'] += $contactTotal;

            // 合并后按创建时间倒序排序
            usort($result['list'], function($a, $b) {
                return strtotime($b['create_time']) - strtotime($a['create_time']);
            });

            // 重新分页
            $result['list'] = array_slice($result['list'], 0, $limit);
        }

        return $this->paginate($result['list'], $result['total'], (int)$page, (int)$limit);
    }

    /**
     * 获取审核类型文本
     */
    private function getReviewTypeText($type)
    {
        $texts = [
            1 => '新增',
            2 => '编辑',
            3 => '删除'
        ];
        return $texts[$type] ?? '未知';
    }

    /**
     * 获取审核状态文本
     */
    private function getStatusText($status)
    {
        $texts = [
            1 => '待审核',
            2 => '审核通过',
            3 => '审核驳回'
        ];
        return $texts[$status] ?? '未知';
    }

    /**
     * 解析变更详情
     */
    private function parseChangeDetails($item)
    {
        $changeDetails = [];

        // 解析原数据和新数据
        $originalData = !empty($item['original_data']) ? json_decode($item['original_data'], true) : null;
        $newData = !empty($item['new_data']) ? json_decode($item['new_data'], true) : null;

        // 如果是新增，直接返回新数据
        if ($item['review_type'] == 1) {
            if ($newData) {
                foreach ($newData as $field => $value) {
                    // 跳过系统字段
                    if (in_array($field, ['id', 'create_time', 'update_time', 'delete_time', 'user_id'])) {
                        continue;
                    }
                    $changeDetails[] = [
                        'field' => $this->getFieldName($field, $item['category']),
                        'old_value' => '',
                        'new_value' => $this->formatFieldValue($field, $value, $item['category'])
                    ];
                }
            }
        }
        // 如果是编辑，比较变更
        elseif ($item['review_type'] == 2) {
            if ($originalData && $newData) {
                foreach ($newData as $field => $newValue) {
                    // 跳过系统字段
                    if (in_array($field, ['id', 'create_time', 'update_time', 'delete_time'])) {
                        continue;
                    }

                    $oldValue = $originalData[$field] ?? '';
                    $oldValueFormatted = $this->formatFieldValue($field, $oldValue, $item['category']);
                    $newValueFormatted = $this->formatFieldValue($field, $newValue, $item['category']);

                    // 只显示有变更的字段
                    if ($oldValueFormatted !== $newValueFormatted) {
                        $changeDetails[] = [
                            'field' => $this->getFieldName($field, $item['category']),
                            'old_value' => $oldValueFormatted,
                            'new_value' => $newValueFormatted
                        ];
                    }
                }
            }
        }
        // 如果是删除，显示删除原因
        elseif ($item['review_type'] == 3) {
            if ($newData && isset($newData['lost_reason'])) {
                $changeDetails[] = [
                    'field' => '删除原因',
                    'old_value' => '',
                    'new_value' => $newData['lost_reason']
                ];
            }
        }

        return $changeDetails;
    }

    /**
     * 获取字段中文名称
     */
    private function getFieldName($field, $category = 'customer')
    {
        $customerFieldMap = [
            'name' => '客户名称',
            'legal_person' => '法定代表人',
            'phone' => '联系电话',
            'email' => '邮箱',
            'address' => '地址',
            'industry' => '行业',
            'scale' => '企业规模',
            'source' => '客户来源',
            'level' => '客户等级',
            'important_level' => '重要程度',
            'status' => '状态',
            'contact_name' => '联系人',
            'contact_phone' => '联系电话',
            'remark' => '备注',
            'lost_reason' => '流失原因',
            'cooperation_time' => '合作时间'
        ];

        $contactFieldMap = [
            'name' => '联系人名称',
            'position' => '职位',
            'phone' => '联系电话',
            'wechat' => '微信',
            'email' => '邮箱',
            'is_primary' => '是否主要联系人'
        ];

        $fieldMap = $category === 'contact' ? $contactFieldMap : $customerFieldMap;

        return $fieldMap[$field] ?? $field;
    }

    /**
     * 格式化字段值
     */
    private function formatFieldValue($field, $value, $category = 'customer')
    {
        // 空值处理
        if ($value === null || $value === '' || $value === 0) {
            return '';
        }

        // 布尔值处理
        if ($field === 'is_cooperation' || $field === 'is_primary') {
            return $value ? '是' : '否';
        }

        // 状态值处理
        if ($field === 'status') {
            return $value == 1 ? '正常' : '禁用';
        }

        // 行业处理（从数据库动态获取）
        if ($field === 'industry') {
            return $this->getIndustryName($value);
        }

        // 规模处理
        if ($field === 'scale') {
            $scaleMap = [
                1 => '微型企业（10人以下）',
                2 => '小型企业（10-50人）',
                3 => '中型企业（50-200人）',
                4 => '大型企业（200-500人）',
                5 => '特大型企业（500人以上）'
            ];
            return $scaleMap[$value] ?? $value;
        }

        // 客户来源处理
        if ($field === 'source') {
            $sourceMap = [
                1 => '网络搜索',
                2 => '客户介绍',
                3 => '电话营销',
                4 => '邮件营销',
                5 => '社交媒体',
                6 => '线下活动',
                7 => '合作伙伴',
                8 => '广告投放',
                9 => '展会',
                10 => '主动咨询',
                11 => '其他'
            ];
            return $sourceMap[$value] ?? $value;
        }

        // 客户等级处理
        if ($field === 'level') {
            $levelMap = [
                1 => 'A类客户',
                2 => 'B类客户',
                3 => 'C类客户'
            ];
            return $levelMap[$value] ?? $value;
        }

        // 重要程度处理
        if ($field === 'important_level') {
            $levelMap = [
                1 => '普通',
                2 => '重要',
                3 => '非常重要'
            ];
            return $levelMap[$value] ?? $value;
        }

        // 时间戳处理（排除时间字段，其他数字保持原样）
        if (is_numeric($value) && !in_array($field, ['phone', 'id', 'id_number', 'user_id', 'department_id'])) {
            if ($value > 1000000000) {
                return date('Y-m-d H:i:s', $value);
            }
        }

        return is_string($value) || is_numeric($value) ? $value : '';
    }

    /**
     * 获取行业名称（从oa_industry表查询）
     */
    private function getIndustryName($industry)
    {
        if (empty($industry)) {
            return '';
        }

        // 获取行业映射表（带缓存）
        static $industryMap = null;
        if ($industryMap === null) {
            $industries = Db::name('industry')
                ->where('status', 1)
                ->select();

            $industryMap = [];
            foreach ($industries as $item) {
                $industryMap[$item['id']] = $item['title'];
            }
        }

        return $industryMap[$industry] ?? '';
    }

    /**
     * 获取企业规模名称
     */
    private function getScaleName($scale)
    {
        if (empty($scale)) {
            return '';
        }

        $scaleMap = [
            1 => '微型企业（10人以下）',
            2 => '小型企业（10-50人）',
            3 => '中型企业（50-200人）',
            4 => '大型企业（200-500人）',
            5 => '特大型企业（500人以上）'
        ];

        return $scaleMap[$scale] ?? $scale;
    }

    /**
     * 清理客户相关缓存（使用统一缓存服务）
     * 使用智能缓存清理机制，支持权限隔离和批量清理
     */
    private function clearCustomerCache()
    {
        try {
            $userId = $this->getUserId();
            
            // 1. 清理业务相关缓存（使用标签批量清理）
            CacheService::clearTag('customer_list');
            CacheService::clearTag('customer_statistics');
            
            // 2. 清理用户相关缓存
            if ($userId) {
                CacheService::clearUserCache($userId);
            }
            
            // 3. 清理标签化缓存（作为备用清理）
            CacheService::clearTag('customer_list');
            CacheService::clearTag('customer_statistics');
            
            // 4. 记录清理日志（生产环境可关闭）
            error_log("Customer cache cleared successfully for user {$userId} at " . date('Y-m-d H:i:s'));
            
            return true;
            
        } catch (\Exception $e) {
            // 记录缓存清理错误，但不中断业务流程
            error_log("Clear customer cache failed: " . $e->getMessage());
            return false;
        }
    }
}
